package com.uduemc.biso.node.web.component.html;

import java.io.StringWriter;
import java.util.Collections;
import java.util.List;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.uduemc.biso.node.core.common.entities.SiteContainer;
import com.uduemc.biso.node.core.common.udinpojo.ContainerCustomcolData;
import com.uduemc.biso.node.core.common.udinpojo.containercustomcol.ContainerCustomcolDataRowCol;
import com.uduemc.biso.node.core.utils.ComponentUtil;
import com.uduemc.biso.node.web.component.html.inter.HIContainerUdin;

@Component
public class HContainerCustomcolUdin implements HIContainerUdin {

	private static String name = "container_customcol";

	@Autowired
	private BasicUdin basicUdin;

	public Template getTemplate(String theme) {
		return basicUdin.getTemplate(name, theme);
	}

	@Override
	public StringBuilder html(SiteContainer siteContainer, List<StringBuilder> childrenHtml) {
		StringBuilder stringBuilder = new StringBuilder();
		String config = siteContainer.getSContainer().getConfig();
		ContainerCustomcolData containerCustomcolData = ComponentUtil.getConfig(config, ContainerCustomcolData.class);
		if (containerCustomcolData == null) {
			return stringBuilder;
		}
		if (StringUtils.isEmpty(containerCustomcolData.getTheme())) {
			return stringBuilder;
		}
		if (StringUtils.isEmpty(containerCustomcolData.getType())) {
			return stringBuilder;
		}
		if (containerCustomcolData.getRow().getCol().size() < 1
				|| containerCustomcolData.getRow().getCol().size() != childrenHtml.size()) {
			return stringBuilder;
		}

		List<ContainerCustomcolDataRowCol> col = containerCustomcolData.getRow().getCol();
		for (int i = 0; i < col.size(); i++) {
			col.get(i).setHtml(childrenHtml.get(i).toString());
		}

		int reversed = containerCustomcolData.getReversed();
		if (reversed == 1) {
			Collections.reverse(col);
		}

		String style = "";
		String rowConfigStyle = containerCustomcolData.getRowConfigStyle();
		if (StringUtils.hasText(rowConfigStyle)) {
			style = "style=\"" + rowConfigStyle + "\"";
		}
		// VelocityContext
		VelocityContext ctx = new VelocityContext();
		// 显示文字还是显示图片
		ctx.put("conid", siteContainer.getSContainer().getId());
		ctx.put("style", style);
		ctx.put("typeClass", containerCustomcolData.getType());

		ctx.put("col", col);

		Template t = getTemplate("default_" + containerCustomcolData.getTheme());
		StringWriter sw = new StringWriter();
		t.merge(ctx, sw);

		stringBuilder.append(sw);

		return stringBuilder;
	}

}
